# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
from typing import List, Dict
from fastapi import Depends, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from exception import AppException
from common.enums.errors import ErrorEnum
from apps.api.config import ApiConfig
from plugins.safe.driver import SecurityDriver


obstruction: Dict[str, List[str]] = {
    "LoginInterceptor": ApiConfig.not_need_login
}


class LoginInterceptor:
    @staticmethod
    async def handler(request: Request, bearer: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
        endpoint: any = request.scope.get("endpoint", lambda: None)
        if endpoint.__module__ == "starlette.staticfiles":
            return True

        # 验登录状态
        token: str = bearer.credentials
        terminal: int = request.state.terminal
        status = await SecurityDriver.module("api").check_login(token, terminal)
        if status == "invalid":
            raise AppException(
                msg="登录失效",
                code=ErrorEnum.TOKEN_VALID.code
            )
        elif status == "disable":
            raise AppException(
                msg="您账号已被禁用",
                code=ErrorEnum.TOKEN_VALID.code
            )
        elif status == "kick":
            raise AppException(
                msg="您已被踢下线喇",
                code=ErrorEnum.TOKEN_VALID.code
            )

        return True
